package com.sc.component;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.sc.exception.ServiceException;
import com.sc.result.Result;
import com.sc.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author JoeZhou
 */
@Slf4j
@RestControllerAdvice(basePackages = {"com.sc"})
public class ExceptionAdvice {

    @ExceptionHandler(ServiceException.class)
    public Object serviceException(ServiceException e) {
        log.error("业务异常: " + e.getMessage());
        return new Result<>(ResultCode.FAILED, e.getMessage());
    }

    @ExceptionHandler(TokenExpiredException.class)
    public Object tokenExpiredException(TokenExpiredException e) {
        log.error("Token异常: " + e.getMessage());
        return new Result<>(ResultCode.TOKEN_FAILED, e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object methodArgumentNotValidException(MethodArgumentNotValidException e) {

        // 获取bindingResult中所有属性错误信息集合中的第一个属性错误
        FieldError firstFieldError = e.getBindingResult().getFieldErrors().get(0);

        // 异常信息 : "xxx实例的xxx属性校验失败: xxx异常信息"
        String message = String.format("%s实例的%s属性校验失败: %s",
                firstFieldError.getObjectName(),
                firstFieldError.getField(),
                firstFieldError.getDefaultMessage());

        // 记录日志
        log.error(message);

        // 响应
        return new Result<>(ResultCode.VALIDATE_FAILED, message);
    }

    @ExceptionHandler(Exception.class)
    public Object exception(Exception e) {
        log.error("其他异常: " + e.getMessage());
        return new Result<>(ResultCode.FAILED, e.getMessage());
    }
}